import { onMounted, reactive, ref, unref, computed } from 'vue';
import { omit, pick } from 'lodash-es';
import type { TablePaginationConfig } from 'antd';
import type { FormInstance } from 'ant-design-vue';

import {
  isFunction,
  isAsyncFunction,
  isArray,
  isBoolean,
  isObject,
} from '@multi-kit/inspect'

import { ACTION_TYPE } from './types';

export function useTableState<T>({ props }) {
  const tableData = ref<T>([]);

  const paginationRef = ref<NonNullable<TablePaginationConfig>>(props.pagination || false);

  const getBindValues = computed(() => {
    const formProps = unref(props);
    const curp = omit(formProps, ['fetchAction']);
    return curp;
  });

  const currRowId = ref<number>(-1);
  const queryCondition = ref<Object>({});

  return {
    tableData,
    paginationRef,
    getBindValues,
    currRowId,
    queryCondition,
  };
}

export function useTableMethods({ props, state }) {
  const { tableData, paginationRef, queryCondition } = state;

  // 更新分页信息
  function updatePagination(pagination: TablePaginationConfig | Boolean) {
    if (isBoolean(paginationRef.value)) {
      paginationRef.value = pagination;
    } else {
      paginationRef.value = {
        ...paginationRef.value,
        ...pagination,
      };
    }
  }

  // 获取表格数据
  const fetchTableData = async (params = {}) => {

    if (isFunction(props.fetchAction) || isAsyncFunction(props.fetchAction)) {
      const data = await props.fetchAction(params);
      if (data?.pagination) {
        updatePagination(data.pagination);
      }

      if (isArray(data?.list)) {
        tableData.value = data?.list;
      } else if (isArray(data)) {
        tableData.value = data;
      } else {
        tableData.value = [];
      }
    }
  };

  // 刷新Table数据
  const reload = async (actionType: ACTION_TYPE | undefined) => {
    const pagination = unref(paginationRef);
    let page = pagination.current;

    switch (actionType) {
      case ACTION_TYPE.REMOVE: {
        if (tableData.value?.length <= 1) {
          page = pagination.current - 1;
        }
        break;
      }
      case ACTION_TYPE.UPDATE:
        break;
      case ACTION_TYPE.CREATE:
      default:
        page = 1;
        break;
    }
    await fetchTableData({
      page,
      pageSize: pagination.pageSize || pagination.defaultPageSize,
    });
  };

  const handleTableChange = (pagination) => {
    fetchTableData({
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...(queryCondition.value || {}),
    });
  };

  return {
    fetchTableData,
    handleTableChange,
    reload,
  };
}

export function useTableForm({ props, fetchTableData, state }) {
  const { queryCondition, paginationRef } = state;
  const { columns } = unref(props);
  const formRef = ref<FormInstance>();

  const formSchemas = computed(() => {
    return columns
      .filter((item) => item.inSearch)
      .map((item) => {
        return {
          component: item.component || 'Input',
          label: item.title,
          name: item.dataIndex,
          dataIndex: item.dataIndex,
          componentProps: item.componentProps,
          colProps: {
            span: 8,
          },
        };
      });
  });

  function invalidClear(target) {
    const ectype = { ...target };
    Object.keys(ectype).forEach((key: string) => {
      if (!ectype[key]) {
        delete ectype[key];
      }
    });
    return ectype;
  }

  function combineParams(params ={}) {
    return isObject(paginationRef.value) ? {...pick(paginationRef.value, ['page','pageSize']), ...params} : params
  }


  const onFinish = (params) => {
    
    const result = invalidClear(params);
    queryCondition.value = result;
  
    fetchTableData(combineParams(queryCondition.value));
  };

  const onReset = () => {
    
    fetchTableData(combineParams());
  };

  const formActionSchemas = [
    {
      component: 'Actions',
      align: 'right',
      actions: [
        {
          label: '重置',
          actionType: 'reset',
          class: 'reset-btn',
        },
        {
          label: '查询',
          type: 'primary',
          actionType: 'submit',
        },
      ],
    },
  ];

  return {
    formRef,
    formSchemas,
    formActionSchemas,
    onFinish,
    onReset,
  };
}
